const sharp = require('sharp')
const fs = require('fs-extra')
const path = require('path')

const imgPath = path.resolve(__dirname, './4.png')


// const {width, height, channels} = await image.metadata()

// console.log(channels);

// console.log(width, height);

/**
 * @name readImage_line
 * @todo 逐行读取图片并转为hex
 * @param {String} imagePath 图片路径
 * @param {Float} scaleRate (0, 1] 缩放比例
 * @param {Function} callback 回调
 */
function readImage_line(imagePath, scaleRate, callback) {
    const image = sharp(imagePath)
    image.metadata()
        .then(({ width, height, channels }) => {

            const toHex = str => str.toString(16).padStart(2, '0')

            width = width * scaleRate
            height = height * scaleRate

            image.raw().toBuffer()
                .then(buffer => {
                    for (let x = 0; x < width; x++) {
                        const row = []
                        for (let y = 0; y < height; y++) {

                            const index = (y * width + x) * channels / scaleRate
                            const hex = `${toHex(buffer[index])}${toHex(buffer[index + 1])}${toHex(buffer[index + 2])}`
                            row.push(hex)
                        }

                        callback && callback(row)
                    }
                })

        })
}

readImage_line(imgPath, .2, dataArray => {
    console.log(dataArray.length);
})